//
// DbService.cpp
// ~~~~~~~~~~~~~~
//
//

// owns the SSQLS: See "5.8. Using an SSQLS in Multiple Modules" in doc/html/userman/ssqls.html.
#include "favorite.h"

#include "DbService.h"

void DbService::initDbCon ()
{
    dbConInfo.dbName   = "stock" ;
    dbConInfo.server   = "localhost" ;
    dbConInfo.user     = "whq" ;
    dbConInfo.password = "" ;

    // Establish the connection to the database server.
    pDbCON = new mysqlpp::Connection
    (
        dbConInfo.dbName.c_str(), dbConInfo.server.c_str(),
        dbConInfo.user.c_str(), dbConInfo.password.c_str()
    );
}

DbService::DbService()
{
    pDbCON = NULL ;
    initDbCon () ;

}

DbService::~DbService()
{
    if (pDbCON)
    {
        delete pDbCON ;
        pDbCON = NULL ;
    }
}

bool DbService::query ( std::string & querySQL, std::vector<favorite> & res )
{
    try
    {
        // Retrieve a subset of targeted table columns, and store
        // the data in a vector of SSQLS structures.
        mysqlpp::Query query = pDbCON->query(querySQL);
        query.storein(res);
    }
    catch (const mysqlpp::BadQuery& er)
    {
        // Handle any query errors
        LOGCON.infoStream() << "Query error: " << er.what() << "\n";
        return false;
    }
    catch (const mysqlpp::BadConversion& er)
    {
        // Handle bad conversions; e.g. type mismatch populating 'favorite'
        LOGCON.infoStream() << "Conversion error: " << er.what() << "\n" <<
        "\tretrieved data size: " << er.retrieved <<
        ", actual size: " << er.actual_size << "\n";
        return false;
    }
    catch (const mysqlpp::Exception& er)
    {
        // Catch-all for any other MySQL++ exceptions
        LOGCON.infoStream() << "Error: " << er.what() << "\n";
        return false;
    }

    return true ;
}

